<?php

namespace App\Service;

use App\Constant\RedisType;
use App\Model\ChatMessage;
use App\Model\ChatUser;
use App\Model\ConsultantDatum;
use App\Model\User;
use App\Model\UserDatum;
use App\Talk\Easemob;
use Exception;
use Hyperf\Di\Annotation\Inject;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class TalkService extends BaseService
{
    /**
     * @Inject()
     * @var Easemob
     */
    public $easemob;


    public $prefix = 'zx';


    /**
     * 获取登录token
     * @param $uid
     * @return array|false
     */
    public function getEasemobToken($uid)
    {


        $chatInfo = ChatUser::where(['uid' => $uid,'huanxin'=>1])->first();

        if (is_null($chatInfo)) {
            $registerStatus = $this->registerEasemob($uid);
            if ($registerStatus){
                $chatInfo = ChatUser::where(['uid' => $uid,'huanxin'=>1])->first();
            }
        }
        if ($chatInfo) {
            return $this->easemob->getToken($this->prefix.$chatInfo['username'], $chatInfo['password']);
        } else {
            return false;
        }

    }

    /**
     * 注册环信用户
     * @param int $uid
     * @return bool|false
     */
    public function registerEasemob(int $uid)
    {

        $chatInfo = ChatUser::where(['uid' => $uid])->first();


        if (is_null($chatInfo)) {
            $rel = ChatUser::addUser($uid);
            if ($rel) {
                $chatInfo = ChatUser::where(['uid' => $uid])->first();
            } else {
                return false;
            }
        }

        if ($chatInfo['huanxin'] == 1) {
            return true;
        }


        $username = $this->prefix . $chatInfo['username'];
        $rel = $this->easemob->createUser($username, $chatInfo['password'], $chatInfo['nickname']);

        if ($rel) {

            ChatUser::where(['uid'=>$uid])->update(['huanxin'=>1]);
            $this->setMetadataToUser($uid);

            return  true;
        } else {
            return false;
        }

    }


    public function setMetadataToUser($uid)
    {

        $userInfo = User::where(['id' => $uid])->select(['num', 'type'])->first();

        if (is_null($userInfo)) {
            return false;
        }

        if ($userInfo['type'] == 1) {
            $info = UserDatum::where(['uid' => $uid])->select(['nickname', 'head'])->first();
        } else {
            $info = ConsultantDatum::where(['uid' => $uid])->select(['cover as heed', 'name as nickname'])->first();
        }

        $metadata = [
            'uid'=>(int)$uid,
            'head' => $info['head'] ? $info['head'] : env('SYS_HEAD', 'https://img.seekingaround.com/seekingaround/dev/2023-06-08/64813f826debaIx8RVQt0gNEkxr0J.png'),
            'nickname' => $info['nickname'] ? $info['nickname'] : getRandomString(6),
            'type' => $userInfo['type']
        ];

        $metadata['ext'] = json_encode($metadata);

        return $this->easemob->setMetadataToUser($this->prefix.$userInfo['num'], $metadata);


    }

    /**
     * 发送简单文本消息
     * @param int $uid 发送人id
     * @param array $users 接收人id 组
     * @param string $msg 发送的消息
     * @return bool
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function sendText(int $uid, array $users, string $msg): bool
    {

        $from = redis()->hGet(RedisType::USER_TO_EASEMOB, strval($uid));
        if ($from == false) {
            $from = ChatUser::where(['uid' => $uid])->value('username');
        }

        foreach ($users as $k => $v) {
            $to = redis()->hGet(RedisType::USER_TO_EASEMOB, strval($v));
            if ($to == false) {
                $to = ChatUser::where(['uid' => $v])->value('username');
            }


            if ($to) {

                logger()->info('消息人', [$to, $from]);
                $this->easemob->sendText([$to], $msg, $from);
            }
        }
        return true;
    }


    /**
     * 同步用户在线状态
     * @param $uid
     * @return bool
     * @throws Exception
     */
    public function syncUserOnlineStatus($uid): bool
    {

        $user = ChatUser::where(['uid' => $uid])->value('username');
        $online = false;
        if ($user) {
            $online = $this->easemob->isUserOnline($user);
        }

        if ($online) {
            redis()->hSet('im:user_' . $uid, 'online', 1);

            $rel = ChatUser::where(['uid' => $uid])->update(['online' => 1]);
            logger()->info('用户同步状态进入结果' . $rel);

            $userInfo = User::find($uid);


            // 不是会员 也不是女性
            if ($userInfo['member'] != 1 && $userInfo['gender'] != 2) {
                $jobService = new JobService();
                $max = random_int(2, 4);
                $jobService->randomReply($uid, 0, 15, $max, $userInfo['lang'] ?? 'en');
            }

        } else {
            logger()->info('不在线');
            redis()->hSet('im:user_' . $uid, 'online', 0);
            ChatUser::where(['uid' => $uid])->update(['online' => 0]);
        }

        return $online;
    }


    /**
     *
     * @param $uid
     * @param int $num
     * @return array|bool|mixed|string
     */
    private function getNoMessageRobotUser($uid, int $num = 0)
    {


        $form = redis()->srandmember(RedisType::ROBOT_USER);
        $exist = ChatMessage::where(['from' => $form, 'to_uid' => $uid])->exists();
        if ($exist) {
            $num++;
            if ($num > 5) {
                return false;
            } else {
                return $this->getNoMessageRobotUser($uid, $num);
            }
        } else {
            return $form;
        }


    }


}
